/*
 * InAndOutputStream.java
 *
 * Copyright(c) 2010
 * Michael Kroez
 * kroez@studiorutton.de
 *
 * All rights reserved.
 *
 * $Id$
 * 
 */

package de.studiorutton.access;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.atomic.AtomicBoolean;

import android.util.Log;

public class InAndOutputStream {
	private static final String TAG = "inandoutputstream";

	private final InputStream in;
	private final OutputStream out;
	private int BUFFER_SIZE = 8192;
	private byte[] buffer;
	private AtomicBoolean cancelReadAndWrite;

	public InAndOutputStream(InputStream in, OutputStream out) {
		if (in == null)
			throw new IllegalArgumentException(
					"InAndOutputStream: Inputstream is null.");
		this.in = in;

		if (out == null)
			throw new IllegalArgumentException(
					"InAndOutputStream: Outputstream is null.");
		this.out = out;

		buffer = new byte[BUFFER_SIZE];
		cancelReadAndWrite = new AtomicBoolean();
	}

	public void setCancelReadAndWrite(boolean cancelReadAndWrite) {
		this.cancelReadAndWrite.set( cancelReadAndWrite );
	}

	public boolean isCancelReadAndWrite() {
		return cancelReadAndWrite.get();
	}

	public int readAndWrite() throws IOException {
		int len;

		cancelReadAndWrite.set( false );

		while ((len = in.read(buffer)) != -1 && !cancelReadAndWrite.get()) {
			out.write(buffer, 0, len);
		
		}
		
		if ( cancelReadAndWrite.get())
			return -2;
		
		if (len == -1)
			return 0;
		else
			return 1;

	}

	public void close() throws IOException {
			out.close();
			in.close();
		
	}
}
